import React, { Component } from 'react'
import PropTypes from 'prop-types'
import './index.css'

export default class index extends Component {

    // 对接收的props进行类型、必要性的限制
    static propTypes = {
        todos: PropTypes.array.isRequired,
        deleteDone: PropTypes.func.isRequired,
        selectAll: PropTypes.func.isRequired
    }

    // 删除已完成的任务
    deleteDone = () => {
        const { todos } = this.props
        for (let i = todos.length - 1; i >= 0; i--) {
            if (todos[i].done) {
                this.props.deleteDone(todos[i].id)
            }
        }
    }

    selectAll = () => {
        const { todos } = this.props
        let doneCount = todos.reduce((prevVal, currVal) => prevVal + (currVal.done ? 1 : 0), 0)
        if (doneCount === todos.length) { // 都已全选
            this.props.selectAll(false)
        } else {
            this.props.selectAll(true)
        }
    }

    render() {
        const { todos } = this.props
        let doneCount = 0, allCount = todos.length
        // forEach
        /* todos.forEach(item => {
            if (item.done) doneCount++
        }) */

        // reduce
        doneCount = todos.reduce((prevVal, currVal) => prevVal + (currVal.done ? 1 : 0), 0)


        let checkAll = doneCount === allCount && allCount > 0 ? true : false

        return (
            <div className="footer">
                <div>
                    <input type="checkbox" checked={checkAll} onChange={this.selectAll} />
                    <div>
                        已完成&nbsp;<span>{doneCount}</span>&nbsp;/ 全部&nbsp;<span>{allCount}</span>
                    </div>
                </div>
                <button onClick={this.deleteDone}>删除已完成任务</button>
            </div>
        )
    }
}
